package com.cloud.service.impl.imports;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONUtil;
import com.cloud.comm.CommonContext;
import com.cloud.mq.topic.RabbitmqConfig;
import com.cloud.pojo.movie.ImportMovie;
import com.cloud.service.ImportMovieService;
import com.cloud.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * @version v1.0
 * @author: TianXiang
 * @description: 上传视频导入
 * @date: 2020/11/24
 */
public class ImportMovieUPLOADServiceImpl implements ImportMovieService {
    private static final Logger LOG = LoggerFactory.getLogger(ImportMovieUPLOADServiceImpl.class.getName());

    @Override
    public void importMovie(ImportMovie importMovie, MultipartFile movieFile, RabbitTemplate rabbitTemplate, RedisTemplate<String,String> redisTemplate) {
        if(null == movieFile)return;
        String fileName = movieFile.getOriginalFilename().trim().replaceAll(" ", "");
        if(this.cacheExistMoive(fileName.split("\\.")[0], redisTemplate)) {
            LOG.error("redis中存在该视频名称, 跳过此操作");
            return;
        }
        importMovie.setMovieName(fileName)
                .setDateDirName(DatePattern.PURE_DATE_FORMAT.format(new Date()))
                .setDirName(UUID.randomUUID().toString().split("-")[0]);
        String uuidDirPath = CommonContext.getContext().getMoviesPath()+ File.separator+ importMovie.getDateDirName()+ File.separator+ importMovie.getDirName();
        String movieFilePath = FileUtils.getMovieFilePath(movieFile, uuidDirPath);
        try {
            FileUtils.multipartFileToFile(movieFile, uuidDirPath, movieFilePath);
        } catch (Exception e) {
            LOG.info("上传文件转换到本地目录失败: {}" ,e.toString());
        }
        File file = new File(movieFilePath);
        if(file.exists()) {
            importMovie.setUuidDirPath(uuidDirPath);
            importMovie.setMovieFilePath(movieFilePath);
            importMovie.setFfmpegExePath(CommonContext.getContext().getFfmpegExePath());
            // 异步消费
            rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPICS, RabbitmqConfig.ROUTINGKEY_TRANSFER_MOVIE, JSONUtil.toJsonStr(importMovie));
        }else {
            LOG.info("没生成文件, 不推送到队列");
        }
    }

}
